import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import type { Site } from '@/types/api'

export const useSiteStore = defineStore('site', () => {
  // 状态
  const currentSite = ref<Site | null>(null)
  const sites = ref<Site[]>([])
  const loading = ref(false)

  // 计算属性
  const currentSiteId = computed(() => currentSite.value?.id || null)
  const currentSiteName = computed(() => currentSite.value?.name || '')
  const hasSites = computed(() => sites.value.length > 0)

  // 方法
  const setCurrentSite = (site: Site | null) => {
    currentSite.value = site
    if (site) {
      localStorage.setItem('currentSite', JSON.stringify(site))
    } else {
      localStorage.removeItem('currentSite')
    }
  }

  const setSites = (siteList: Site[]) => {
    sites.value = siteList
  }

  const addSite = (site: Site) => {
    sites.value.push(site)
  }

  const updateSite = (updatedSite: Site) => {
    const index = sites.value.findIndex(site => site.id === updatedSite.id)
    if (index !== -1) {
      sites.value[index] = updatedSite
      
      // 如果更新的是当前站点，也更新当前站点信息
      if (currentSite.value?.id === updatedSite.id) {
        setCurrentSite(updatedSite)
      }
    }
  }

  const removeSite = (siteId: string | number) => {
    sites.value = sites.value.filter(site => site.id !== siteId)
    
    // 如果删除的是当前站点，清空当前站点
    if (currentSite.value?.id === siteId) {
      setCurrentSite(null)
    }
  }

  const getSiteById = (siteId: string | number): Site | undefined => {
    return sites.value.find(site => site.id === siteId)
  }

  const setLoading = (isLoading: boolean) => {
    loading.value = isLoading
  }

  const initFromStorage = () => {
    const storedSite = localStorage.getItem('currentSite')
    if (storedSite) {
      try {
        currentSite.value = JSON.parse(storedSite)
      } catch (error) {
        console.error('Failed to parse stored site data:', error)
        localStorage.removeItem('currentSite')
      }
    }
  }

  const clear = () => {
    currentSite.value = null
    sites.value = []
    loading.value = false
    localStorage.removeItem('currentSite')
  }

  // 初始化
  initFromStorage()

  return {
    // 状态
    currentSite,
    sites,
    loading,
    
    // 计算属性
    currentSiteId,
    currentSiteName,
    hasSites,
    
    // 方法
    setCurrentSite,
    setSites,
    addSite,
    updateSite,
    removeSite,
    getSiteById,
    setLoading,
    initFromStorage,
    clear
  }
})
